//
//  CoreUserPasswordTextFieldComponent.m
//  CoreUser
//
//  Created by Demi on 20/04/2017.
//  Copyright © 2017 Azazie. All rights reserved.
//

#import "CoreUserPasswordTextFieldComponent.h"

#import <base/base.h>
#import <Masonry/Masonry.h>
#import <ReactiveObjC/ReactiveObjC.h>

@implementation CoreUserPasswordTextFieldComponent

- (void)prepare
{
    [super prepare];
    
    self.placeholderLabel.text = @"Password";
    
    self.textField.disablesActionMenu = YES;
    self.textField.keyboardType = UIKeyboardTypeAlphabet;
    self.textField.secureTextEntry = YES;
    self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"SHOW" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor darkGrayTextColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:UIFontExtraSmallSize];
    @weakify(self);
    [[[[button rac_signalForControlEvents:UIControlEventTouchUpInside] doNext:^(UIButton * _Nullable x) {
        @strongify(self);
        [x setTitle:self.textField.secureTextEntry ? @"HIDE" : @"SHOW" forState:UIControlStateNormal];
    }] map:^id _Nullable(__kindof UIControl * _Nullable value) {
        @strongify(self);
        return @(!self.textField.secureTextEntry);
    }] subscribeNext:^(NSNumber * _Nullable x) {
        @strongify(self);
        if (SYSTEM_VERSION_LESS_THAN(@"10.0") && self.textField.isFirstResponder)
        {
            [self.textField resignFirstResponder];
            self.textField.secureTextEntry = x.boolValue;
            [self.textField becomeFirstResponder];
        }
        else
        {
            self.textField.secureTextEntry = x.boolValue;
        }
    }];
    [self addSubview:button];
    [self.textField mas_updateConstraints:^(MASConstraintMaker *maker){
        maker.trailing.equalTo(self).offset(-45.f);
    }];
    [button mas_makeConstraints:^(MASConstraintMaker *maker){
        // maker.top.and.bottom.equalTo(self.textField);
        /// add area for touch
        maker.top.equalTo(self.textField).offset(-10.f);
        maker.bottom.equalTo(self.textField).offset(10.f);
        
        maker.trailing.equalTo(self);
        maker.leading.equalTo(self.textField.mas_trailing);
    }];
    
    RAC(button, hidden) = RACObserve(self, invalid);
}

- (BOOL)validate
{
    BOOL isValid = [self.textField.text isValidPassword];
    if (!isValid)
    {
        self.invalid = YES;
    }
    return isValid;
}

- (void)setInvalid:(BOOL)invalid
{
    if (invalid)
    {
        if (self.textField.text.length > 0)
        {
            self.errorLabel.text = @"Your password should be at least 5 characters.";
        }
        else
        {
            self.errorLabel.text = @"Please enter your password.";
        }
    }
    [super setInvalid:invalid];
}

@end
